package megrez.job.custom.component;

import java.util.Date;

import lombok.Data;
import megrez.job.custom.domain.TaskState;

/**
 * 任务监控信息
 * 
 * @author Lucky Yang
 * @since 2.6.9
 */
@Data
public class Monitor{
    /** 启动时间 */
    private Date startUpTime;
    /** 最后运行时间 */
    private Date lastRunTime;
    /** 运行次数 */
    private int numOfRuns;
    /** 失败次数 */
    private int numOfErrors;
    /** 任务状态 */
    private TaskState state;
    /** 最近的消息 */
    private String message;
    /** 最近消耗时间,毫秒 */
    private long costTime;
    /** 是否存在计划任务 */
    private boolean scheduled;

    public Monitor() {
        this.scheduled = false;
        this.state = TaskState.STOPPED;
    }

    public Monitor(Monitor m) {
        this.startUpTime = m.startUpTime;
        this.lastRunTime = m.lastRunTime;
        this.numOfRuns = m.numOfRuns;
        this.numOfErrors = m.numOfErrors;
        this.state = m.state;
        this.message = m.message;
        this.costTime = m.getCostTime();
        this.scheduled = m.isScheduled();
    }

    public Monitor start() {
        scheduled = true;
        startUpTime = new Date();
        lastRunTime = new Date();
        numOfRuns = 0;
        numOfErrors = 0;
        state = TaskState.STARTED;
        message = state.note;
        costTime = 0;
        return this;
    }

    public Monitor run() {
        costTime = calCostTime();
        lastRunTime = new Date();
        numOfRuns = numOfRuns + 1;
        state = TaskState.RUNNING;
        message = state.note;
        return this;
    }

    public Monitor complete() {
        costTime = calCostTime();
        lastRunTime = new Date();
        state = TaskState.COMPLETE;
        message = state.note;
        return this;
    }

    public Monitor stop() {
        scheduled = false;
        costTime = calCostTime();
        lastRunTime = new Date();
        state = TaskState.STOPPED;
        message = state.note;
        return this;
    }

    public Monitor error(String error) {
        costTime = calCostTime();
        lastRunTime = new Date();
        numOfErrors = numOfErrors + 1;
        state = TaskState.ERROR;
        message = error;

        return this;
    }

    
    private long calCostTime() {
        return (new Date()).getTime() - lastRunTime.getTime();
    }

}
